package touro.mancala.slave;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

import touro.mancala.core.Constants;


public class SlaveSocket extends Socket implements Runnable {
	
	private static final Logger logger = Logger.getLogger(SlaveSocket.class.getName());
	
	Slave slave;
	private Socket socket;
	private boolean closed;

	public SlaveSocket(String ipAddress) throws IOException{
		this(ipAddress, 4);
	}
	
	public SlaveSocket(String ipAddress, int levels) throws IOException {
		slave = new Slave(levels);
		logger.log(Level.INFO, "Attempting to connect to " + ipAddress);
		socket=new Socket(ipAddress, Constants.SLAVE_PORT);
		logger.log(Level.INFO, "Connected to " + ipAddress);
		closed=false;
	}

	//this allows us to close the socket
	public void close(){
		try {
			closed=true;
			socket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void run(){
		while(!closed){
			listen();
		}
	}
	
	private void listen(){
		try{
			InputStream in=socket.getInputStream();
			Scanner scanner=new Scanner(in);
			String line = scanner.nextLine();
			logger.log(Level.INFO, "Read " + line);
			String score=slave.getScore(line);
			logger.log(Level.INFO, "The output of this board is " + score);
			
			OutputStream out=socket.getOutputStream();
			
			String RESPONSE=score+"\n";

			logger.log(Level.INFO, "Writing " + score);
			out.write(RESPONSE.getBytes());
			out.flush();
		}
		catch (IOException e) {
			e.printStackTrace();
		}
	}
}

